package com.hemerasolutions.v2trainer.dao;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.faces.context.FacesContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.ServletContext;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hemerasolutions.v2trainer.dao.interfaces.PhotoDaoInterface;
import com.hemerasolutions.v2trainer.model.multimedia.Photo;
import com.hemerasolutions.v2trainer.model.multimedia.Photo_;
import com.hemerasolutions.v2trainer.util.Utility;

@Repository(value = "photoDao")
public class PhotoDao extends BaseDao<Photo> implements PhotoDaoInterface{
	private static final long serialVersionUID = 1L;

	
	@Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public Photo save(Photo object) throws ExceptionDao {
		
		try{
			return super.save(object);
		}catch(ExceptionDao e){
			e.printStackTrace();
			throw e;
		}
	}
	
	@Override	
	public String persistInFile(Photo photo) throws ExceptionDao{

		ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
		
		String path = servletContext.getRealPath("/");
		
		if(photo.getLocation() != null && !photo.getLocation().equals("")){
			this.deleteFile(photo.getLocation());
		}
		
		String filename = Utility.randomString(20);
		
		// Prepare file and outputstream.
		File file = null;
        OutputStream output = null;
        
        try {
            // Create file with unique name in upload folder and write to it.
            file = new File(path + photo.getFolder() + filename + ".jpg");
            output = new FileOutputStream(file);
            IOUtils.copy(new ByteArrayInputStream(photo.getContent()), output);
            System.out.println("Foto salva em: " + path + photo.getFolder() );
            photo.setPersisted(true);
            return file.getName();
            
        } catch (IOException e) {
            // Cleanup.
            if (file != null) {
               	file.delete();
            }
            e.printStackTrace();
            throw new ExceptionDao(e);
        } finally {
            IOUtils.closeQuietly(output);
        }		
	}

	private void deleteFile(String location){
		
	}

	@Override
	public Photo findByName(String name) {
	
		CriteriaBuilder cb = this.getEntityManager().getCriteriaBuilder();

		CriteriaQuery<Photo> cq  = cb.createQuery(Photo.class);
		
		Root<Photo> photo = cq.from(Photo.class);

		Predicate pred = cb.equal(cb.upper(photo.<String>get("name")),name.toString().toUpperCase());

	    cq.where(pred);
	 
	    return super.getEntityManager().createQuery(cq).getSingleResult();
	}

	@Override
	public Photo findByLocation(String name) {
		CriteriaBuilder cb = this.getEntityManager().getCriteriaBuilder();

		CriteriaQuery<Photo> cq  = cb.createQuery(Photo.class);
		
		Root<Photo> photo = cq.from(Photo.class);

		Predicate pred = cb.equal(photo.<String>get(Photo_.location),name);

	    cq.where(pred);
	 
	    return super.getEntityManager().createQuery(cq).getResultList().get(0);
	}

	@Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public Photo saveEntry(Photo photo) {
		return super.save(photo);
	}
	
}
